<template>
	<view>
		<view class="from_list">
			<view class="from_item" v-for="(item, index) in list" :key="index">
				<text class="label" :class="{ 'textareaLabel': item.label == '门店描述' }">{{ item.label }}</text>
				<input v-model="item.value" class="input" v-if="item.type == 'text' || item.type == 'number'"
					:placeholder="item.placeholder" :type="item.type" />
				<textarea style="height: 140rpx;" cols="10" rows="5" v-model="item.value" class="input"
					v-if="item.type == 'textArea'" :placeholder="item.placeholder"></textarea>
				<!-- <view v-if="item.type=='text'||item.type=='number'">
					{{item.value}}
				</view> -->
				<view  class="hiddenText" style="flex: 1; text-align: left;" v-if="item.type == 'loc'" @click="chooseLocation">
					{{ item.value ? item.value : item.placeholder }}
				</view>
				<view class="select_type" v-if="item.type == 'select'" @click="selectType">
					<text>{{ item.value }}</text>
					<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/arror_right.png" mode=""></image>
				</view>
				<!-- 	<view class="choose_location" v-if="item.type=='loc'" @click="chooseLocation">
					<text>定位</text>
				</view> -->

			</view>
			<!-- <view class="from_item">
				<text class="label">营业时间</text>
				<text style="text-align: right;" class="input" @tap="showPicker">
					{{ timeRanges || '请选择营业时间' }} </text>
				<tpf-time-range ref="time" :startTime="startTime" :startDefaultTime="startDefaultTime"
					:endTime="endTime" :endDefaultTime="endDefaultTime" @timeRange="timeRange">
				</tpf-time-range>
			</view> -->
			<view class="from_item">
				<text class="label">登陆账号</text>
				<view class="input">{{ shopInfo.LoginName }}</view>
			</view>
			<view class="from_item">
				<text class="label">登陆密码</text>
				<input v-model="password" class="input" placeholder="修改登陆密码" />
				<button class="confirm" v-if="password.length > 0" @click="changePas">确认修改</button>
			</view>
			<!-- 上传图片 -->
			<view class="upload">
				<text>门店照片(如门头、门店内照片):</text>
				<view class="img_box">
					<view class="img" v-for="(item, i) in imgArr" :key="i">
						<image :src="item.tempUrl" mode="aspectFill" @click="priviewPic(i)"></image>
						<view class="icon" @click.stop="delImg(i)">
							<image src="https://golfdate.oss-cn-shenzhen.aliyuncs.com/upload/1710154762492571.png"
								mode=""></image>
						</view>
					</view>
					<view class="img addimg" @tap="upload" v-if="imgArr.length < 3">
						<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/upload.png" mode="">
						</image>
					</view>
				</view>
			</view>
			<view class="button_view">
				<button @click="submit">修改</button>
			</view>
		</view>
		<u-picker :show="show" :columns="columns" @confirm="confirm"></u-picker>
	</view>
</template>

<script>
import util from '@/common/util'
const env = require('@/common/ossutil/config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
export default {
	data() {
		return {
			startTime: "00:00",
			startDefaultTime: "00:00",
			endTime: "24:00",
			endDefaultTime: "00:00",
			list: [{
				label: '联系人',
				value: '',
				placeholder: '请输入姓名',
				type: 'text'
			},
			{
				label: '联系电话',
				value: '',
				placeholder: '请输入电话',
				type: 'number'
			},
			{
				label: '门店名称',
				value: '',
				placeholder: '请输入门店名称',
				type: 'text'
			},
			{
				label: '门店位置',
				value: '',
				placeholder: '点击定位获取',
				type: 'loc',
				latitude: '',
				longitude: '',
				province: '',
				city: '',
			},
			{
				label: '门店描述',
				value: '',
				placeholder: '请输入门店描述',
				type: 'textArea'
			},
			],
			columns: [
				['大学内或周边打印店', '中小学周边打印店', '政府周边打印店', '其他']
			],
			// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
			radiovalue1: '',
			show: false,
			imgArr: [],
			timeRanges: '',
			ShopID: '',
			password: '',
			shopInfo: {},
		}
	},
	onLoad(option) {
		if (option.ShopID) {
			this.ShopID = option.ShopID
			this.getStoreInfo(option.ShopID)
		}
	},
	methods: {
		async changePas() {
			let that = this
			uni.showModal({
				title: `确认修改密码吗?`,
				content: '确认修改密码吗?',
				success: async () => {
					let res = await that.$api.post('Business/SetUpPwd', { Pwd: that.password, OldPwd: that.shopInfo.OldPwd, LoginID: that.shopInfo.LoginID })
					if (res?.data?.IsSuccess) {
						that.shopInfo.OldPwd = that.password
						this.$pv.msg('密码修改成功')
					} else {
						this.$pv.msg('密码修改失败，请重试')
					}
				}
			})
		},
		priviewPic(i) {
			console.log(i);
			let photoList = this.imgArr.map(item => {
				return item.tempUrl;
			});
			uni.previewImage({
				current: i,
				urls: photoList
			});

		},

		async getStoreInfo(id) {
			let res = await this.$api.post('Business/GetBusinessInformation', {
				ShopID: id
			})
			console.log(res);
			this.list = this.updateListWithData(this.list, res.data);
			let arr = res.data.ShopImgs.split(',')
			arr.forEach((item) => {
				this.imgArr.push({
					tempUrl: item,
					netPath: item
				})
			})
			this.timeRanges = res.data.BusinessHours
			this.password = res.data.Pwd
			this.shopInfo = res.data

		},
		updateListWithData(list, data) {
			return list.map(item => {
				switch (item.label) {
					case '联系人':
						return {
							...item, value: data.Contacts || ''
						};
					case '联系电话':
						return {
							...item, value: data.ServerPhone || ''
						};
					case '门店名称':
						return {
							...item, value: data.ShopName || ''
						};
					case '门店位置':
						return {
							...item,
							value: data.Address || '',
							latitude: data.Latitude || '',
							longitude: data.Longitude || '',
							province: data.Province || '',
							city: data.City || ''
						};
					case '门店描述':
						return {
							...item, value: data.Description || ''
						};
					default:
						return item;
				}
			});
		},


		showPicker() {
			this.$refs['time'].open();
		},
		timeRange(e) {
			this.timeRanges = e.join('-')
			console.log(e);
		},
		confirm(e) {
			console.log('confirm', e)
			this.show = false
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = e.value[0]
		},
		async submit() {

			// 提取 netPath，并生成以逗号分隔的字符串
			const netPaths = this.imgArr
				.filter(item => item.netPath) // 过滤掉没有 netPath 的项
				.map(item => item.netPath) // 提取 netPath
				.join(','); // 连接成逗号分隔的字符串

			// 验证所有必填字段不能为空
			const requiredFields = {
				ShopName: this.list[2].value,
				Address: this.list[3].value,
				Longitude: this.list[3].longitude,
				Latitude: this.list[3].latitude,
				ServerPhone: this.list[1].value,
				Contacts: this.list[0].value,
				// Description: this.list[4].value,
				Province: this.list[3].province,
				City: this.list[3].city,
				// BusinessHours: this.timeRanges
			};
			console.log(requiredFields);

			for (const [key, value] of Object.entries(requiredFields)) {
				if (value === undefined || value === null || value === '') {
					uni.showToast({
						title: `请完善表格`,
						icon: 'none'
					})
					return
				}
			}

			// 验证 ServerPhone 是否符合电话号码格式
			const phoneRegex = /^[0-9]{10,15}$/; // 可以根据需要调整正则表达式
			if (!phoneRegex.test(requiredFields.ServerPhone)) {
				uni.showToast({
					title: `请输入正确的手机号`,
					icon: 'none'
				})
				return
			}

			// 构造要发送的对象
			const obj = {
				ShopImgs: netPaths,
				ShopName: requiredFields.ShopName,
				Address: requiredFields.Address,
				Longitude: requiredFields.Longitude,
				Latitude: requiredFields.Latitude,
				ServerPhone: requiredFields.ServerPhone,
				Status: 0,
				Contacts: requiredFields.Contacts,
				Guid: uni.getStorageSync('guid'),
				Description: this.list[4].value || '',
				Province: requiredFields.Province,
				City: requiredFields.City,
				BusinessHours: requiredFields.BusinessHours,
				ShopID: this.ShopID,
				OldPwd: this.shopInfo.OldPwd,
				Pwd: this.password,
				LoginID: this.shopInfo.LoginID
			};

			// 发送 API 请求
			const res = await this.$api.post('Business/SetBusInformation', {
				...obj
			});
			console.log(res);
			if (res.data) {
				uni.showToast({
					title: `修改成功`,
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 500)
			}



		},
		async uploading(url, tempKey) {
			console.log('url ----------' + url);

			const r = await this.$upload(url, (pro) => {
				this.imgArr.forEach((item) => {
					if (item.tempKey == tempKey) {
						item.pro = pro;
					}
				});
			});
			this.imgArr.forEach((item) => {
				if (item.tempKey == tempKey) {
					item.netPath = r;
				}
			});

			console.log('upload file ' + r);
			// this.formdata.PhotoUrl.push(r);
			// this.formdata.PhotoUrl = r
		},
		upload() {
			let _this = this;
			let diyCount = 3 - this.imgArr.length
			uni.chooseMedia({
				count: diyCount,
				mediaType: ['image'],
				sourceType: ['album', 'camera'],
				maxDuration: 30,
				camera: 'back',
				success(res) {
					console.log(res);
					res.tempFiles.forEach(async (item) => {
						let o = {
							duration: 0,
							fileType: item.fileType,
							tempUrl: item.tempFilePath,
							flieUrl: item.tempFilePath,
							tempKey: uni.$u.guid(8),
							pro: 0,
						};

						_this.imgArr.push(o);

						let rex = await _this.uploading(o.flieUrl, o.tempKey);
						console.log('rex-------', rex);
					});
				},
			});
		},
		delImg(i) {
			this.imgArr.splice(i, 1);
			// this.formdata.Images.splice(i, 1);
		},

		resetType() {
			this.radiovalue1 = ''
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = ''
		},
		selectType() {
			// this.show = true
		},
		chooseLocation() {
			let that = this
			uni.chooseLocation({
				async success(res) {
					let res2 = await util.getAddress(res)
					console.log(res2);
					const index = that.list.findIndex(item => item.type === 'loc');
					console.log(index);
					console.log(res);
					that.list[index].value = res.address
					that.list[index].latitude = res.latitude
					that.list[index].longitude = res.longitude
					that.list[index].province = res2.result.address_component.province
					that.list[index].city = res2.result.address_component.city

				},
				fail(err) {
					console.log(err);
				}
			})
		},
		radioChange(n) {
			const index = this.list.findIndex(item => item.type === 'select');
			this.list[index].value = n
		}
	}
}
</script>

<style lang="scss" scoped>
.confirm {
	width: 100rp;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #3572FE;
	color: #fff;
	border-radius: 10rpx;
	margin: 0 20rpx;
	font-size: 24rpx;
	box-sizing: content-box;
	padding: 10rpx;
}

.img:nth-child(3n) {
	margin-right: 0;
}

.addimg {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F6F6F6;

	image {
		width: 80rpx;
		height: 80rpx;
	}
}

.img_box {
	display: flex;
	align-items: center;
	// justify-content: space-evenly;
	flex-wrap: wrap;
	margin-top: 20rpx;
}

.videobox {
	padding: 32rpx;
	position: relative;

	>view {
		width: 100%;
		height: 300rpx;
		border-radius: 16rpx;
		overflow: hidden;

		video {
			width: 100%;
			height: 100%;
		}
	}

	.icon {
		position: absolute;
		right: 10rpx;
		top: 10rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		// border-radius: 50%;
		z-index: 5;

		image {
			width: 40rpx;
			height: 40rpx;
			background: #fff;
			border-radius: 50%;
		}
	}
}

.img {
	width: 200rpx;
	height: 200rpx;
	border-radius: 8rpx;
	margin-right: 16rpx;
	margin-top: 16rpx;
	// overflow: hidden;
	position: relative;

	image {
		border-radius: 8rpx;
		width: 100%;
		height: 100%;
	}

	.icon {
		position: absolute;
		right: -20rpx;
		top: -14rpx;
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		// border-radius: 50%;
		z-index: 50;

		image {
			width: 40rpx;
			height: 40rpx;
			background: #fff;
			border-radius: 50%;
		}
	}
}

.img:nth-child(3n) {
	margin-right: 0;
}

.addimg {
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #F6F6F6;

	image {
		width: 80rpx;
		height: 80rpx;
	}
}

.button_view {
	position: fixed;
	bottom: 80rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 80%;
	z-index: 99;

	button {
		color: white;
		background: #3572FE;
		border-radius: 15rpx;
		margin-right: 24rpx;
	}
}

.upload {
	margin: 20rpx;
}

.button_group {
	display: flex;
	align-items: center;

	button {
		width: 50%;
		display: flex;
		align-items: center;
		font-size: 28rpx;
		justify-content: center;
	}
}

.popup_container {
	padding: 30rpx;

	.type {
		height: 80rpx;
		display: flex;
		// align-items: center;
	}
}

.input {
	flex: 1;
	text-align: right;
}

.choose_location {
	width: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1rpx solid #3572fe;
	border-radius: 30rpx;
	height: 50rpx;

	text {
		color: #3572fe;
		font-size: 28rpx
	}
}

.select_type {
	display: flex;
	align-items: center;
	font-size: 24rpx;

	image {
		width: 25rpx;
		height: 25rpx;
	}
}

.label {
	min-width: 150rpx;
}
.textareaLabel {
	margin-bottom: auto;
	padding-top: 16rpx;
}

.from_list {
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding-bottom: 170rpx;
	.from_item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 20rpx;
		min-height: 120rpx;
		border-bottom: 1rpx solid #eeeeee;

		text {
			white-space: normal;
		}
	}

	
}
</style>